package com.domainchen.framework.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author  domainchen
 * @version 2016年3月9日 下午11:58:03   
 * @类说明 类型转换工具
 */
public class CastUtil {
	private static Logger logger = LoggerFactory.getLogger(CastUtil.class);

	/*
	 * 转为String
	 */
	public static String castString(Object obj) {
		return CastUtil.castString(obj, "");
	}

	/*
	 * 转为String(提供默认值)
	 */
	public static String castString(Object obj, String defaultValue) {
		return obj != null ? String.valueOf(obj) : defaultValue;
	}

	/*
	 * 转为Double
	 */
	public static double castDouble(Object obj) {
		return CastUtil.castDouble(obj, 0);
	}

	/*
	 * 转为Double (提供默认值)
	 */
	public static double castDouble(Object obj, double defaultValue) {
		double doubleValue = defaultValue;
		if (null != obj) {
			String doubleStr = castString(obj);
			if (StringUtils.isNotEmpty(doubleStr)) {
				try {
					doubleValue = Double.parseDouble(doubleStr);
				} catch (Exception ex) {
					doubleValue = defaultValue;
					logger.error("CastUtil--> parse Double failure" + ex.getMessage());
				}
			}
		}
		return doubleValue;
	}

	/**
	 * 转为long型
	 * 
	 * @param obj
	 * @return
	 */
	public static long castLong(Object obj) {
		return CastUtil.castLong(obj, 0);
	}

	/**
	 * 转为long型(提供默认值)
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static long castLong(Object obj, long defaultValue) {
		long longValue = defaultValue;
		if (null != obj) {
			String longStr = castString(obj);
			if (StringUtils.isNotEmpty(longStr)) {
				try {
					longValue = Long.parseLong(longStr);
				} catch (Exception ex) {
					longValue = defaultValue;
					logger.error("CastUtil--> parse Long failure" + ex.getMessage());
				}
			}
		}
		return longValue;
	}

	/**
	 * 转为int型
	 * 
	 * @param obj
	 * @return
	 */
	public static int castInt(Object obj) {
		return CastUtil.castInt(obj, 0);
	}

	/**
	 * 转为int型(提供默认值)
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static int castInt(Object obj, int defaultValue) {
		int intValue = defaultValue;
		if (null != obj) {
			String intStr = castString(obj);
			if (StringUtils.isNotEmpty(intStr)) {
				try {
					intValue = Integer.parseInt(intStr);
				} catch (Exception ex) {
					intValue = defaultValue;
					logger.error("CastUtil--> parse int failure" + ex.getMessage());
				}
			}
		}
		return intValue;
	}

	/**
	 * 转为 boolean
	 * @param obj
	 * @return
	 */
	public static boolean castBoolean(Object obj) {
		return CastUtil.castBoolean(obj, false);
	}

	/**
	 * 转为 boolean(提供默认值)
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static boolean castBoolean(Object obj, boolean defaultValue) {
		boolean booleanValue = defaultValue;
		if (null != obj) {
			booleanValue = Boolean.parseBoolean(castString(obj));
		}
		return booleanValue;
	}
}
